<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="项目名称/项目编号" prop="deptName">
        <el-select v-model="queryParams.deptName" filterable remote placeholder="请输入项目名称" :remote-method="remoteMethod"
          @change="changeFun" :loading="loading_options">
          <el-option v-for="item in project_list" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="当前状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['sop:manage:add']"
          >新增</el-button>
        </el-col> -->
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="deptList" row-key="deptId" ref="table1"
      :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column prop="deptName" label="名称" width="260"></el-table-column>
      <el-table-column prop="deptNum" label="编号" width="200"></el-table-column>
      <el-table-column prop="orderNum" label="排序" width="200"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="工序图片" width="100">
        <template slot-scope="scope">
          <!-- 图片上传 -->
          <!-- <el-image class="imagePreview" :src="base_url + scope.row.email"
            :preview-src-list="[base_url + scope.row.email]">
            <div slot="error" class="image-slot">

            </div>
          </el-image> -->
          <!-- 图片编辑 -->
          <el-image class="imagePreview" :src="scope.row.phone" :preview-src-list="[scope.row.phone]">
            <div slot="error" class="image-slot">

            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>

        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['sop:manage:edit']"
            v-if="scope.row.ancestors.split(',').length == 1 ? userName == 'admin' ? true : false : true">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
            v-hasPermi="['sop:manage:add']" v-if="scope.row.ancestors.split(',').length < 5">新增</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="titleJson.title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="父级" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择父级"
                disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="titleJson.name" prop="deptName">
              <!-- <el-input v-if="titleJson.name != '工序名称' || titleJson.name != '组件名称'" v-model="form.deptName" placeholder="请输入名称" /> -->
              <!-- 远程搜索 -->
              <el-autocomplete v-if="open" v-model="form.deptName" :fetch-suggestions="querySearchAsync" :trigger-on-focus="false"
                placeholder="请输入内容" @select="handleSelect">
                <!-- 自定义模板 -->
                <template slot-scope="{ item }">
                  <div class="name">{{ item.deptName }}</div>
                  <el-image class="imagePreview" :src="item.phone" :preview-src-list="[item.phone]">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                      {{ item.phone ? '加载失败，请重试！' : '暂无图片' }}
                    </div>
                  </el-image>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="titleJson.name == '项目名称'">
          <el-col :span="12">
            <el-form-item label="项目编号" prop="deptNum">
              <!-- 去掉空格 -->
              <el-input v-model.trim="form.deptNum" placeholder="编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="当前状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{
                  dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="titleJson.name == '工序名称' || titleJson.name == '组件名称'">
          <el-col :span="20">
            <el-form-item label="图片">
              <!-- 图片上传 -->
              <!-- <ImageUpload :limit="1" :value="form.email" :fileSize="5" @onUploaded="handleImgUplaoded"
                @onRemoved="handleImgRemoved"></ImageUpload> -->
              <!-- 图片编辑 -->
              <el-image class="imagePreview" :src="form.phone" :preview-src-list="[form.phone]" :key="form.phone">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                  {{ form.phone ? '加载失败，请关闭弹框后重试！' : '暂无图片' }}
                </div>
              </el-image>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <!-- 点击全屏弹框 -->
            <el-button type="primary" @click="click_img_ground">编辑图片</el-button>
          </el-col>
        </el-row>
        <!-- 安装后效果图片上传 -->
        <el-row v-if="titleJson.name == '工序名称' || titleJson.name == '组件名称'">
          <el-col :span="24">
            <el-form-item label="安装后效果" label-width="90px">
              <!-- 图片上传 -->
              <ImageUpload :limit="1" :value="form.email" :fileSize="5" @onUploaded="handleImgUplaoded"
                @onRemoved="handleImgRemoved"></ImageUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="titleJson.name == '工序名称' || titleJson.name == '组件名称'">
          <el-col :span="24">
            <div>
              <el-form-item label="备件信息">
                <el-button type="primary" @click="addRow">添加一行</el-button>
              </el-form-item>
              <!-- 表格 -->
              <el-table :data="form.tableData" border style="width: 100%" height="250">
                <el-table-column prop="id" label="序号" width="85" show-overflow-tooltip>
                  <template #default="scope">
                    <div class="scroll-container">
                      <el-input v-model="scope.row.id" placeholder="请输入序号" type="number"
                        class="scroll-input"></el-input>
                      <div class="scroll-text" v-if="scope.row.id > 9">
                        {{ scope.row.id }}
                      </div>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="name" label="名称" width="90" show-overflow-tooltip>
                  <template #default="scope">
                    <div class="scroll-container">
                      <el-input v-model="scope.row.name" placeholder="请输入名称" class="scroll-input"></el-input>
                      <div class="scroll-text" v-if="scope.row.name.length > 0">
                        {{ scope.row.name }}
                      </div>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="address" label="件号" show-overflow-tooltip>
                  <template #default="scope">
                    <div class="scroll-container">
                      <el-input v-model="scope.row.address" placeholder="请输入件号" class="scroll-input"
                        style="width: 200px"></el-input>
                      <div class="scroll-text" v-if="scope.row.address.length > 0">
                        {{ scope.row.address }}
                      </div>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="age" label="数量" width="85" show-overflow-tooltip>
                  <template #default="scope">
                    <div class="scroll-container">
                      <el-input v-model="scope.row.age" placeholder="请输入数量" type="number"
                        class="scroll-input"></el-input>
                      <div class="scroll-text" v-if="scope.row.age > 9">
                        {{ scope.row.age }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="85">
                  <template #default="scope">
                    <el-button type="danger" size="small" @click="deleteRow(scope.$index)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑图片全屏弹框 -->
    <el-dialog title="编辑图片" :visible.sync="img_ground_flage" :fullscreen="true" :close-on-click-modal="false">
      <div class="img_box">
        <Img_ground :form="form" ref="img_ground" v-if="img_ground_flage"></Img_ground>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="img_ground_flage = false">取 消</el-button>
        <el-button type="primary" @click="img_ground_flage_btn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild, listDeptPost, updateDeptOrder, selectDateNo } from "@/api/sop/manage";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Cookies from "js-cookie";
import ImageUpload from "@/components/ImageUpload/index.vue"
// 引入图片编辑组件
import Img_ground from "../comment/img_ground.vue";

// 拖拽
import Sortable from 'sortablejs'

export default {
  name: "Dept",
  dicts: ['sys_normal_disable'],
  components: { Treeselect, ImageUpload, Img_ground },
  data() {
    return {
      // 初始化表格数据
      tableData: [
        { name: '张三', age: 25, address: '北京市' },
        { name: '李四', age: 30, address: '上海市' },
      ],
      // 当前用户
      userName: Cookies.get("username"),
      // 标题及名称
      titleJson: {
        title: "新增",
        name: "部门"
      },
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "父级不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" }
        ],
        // phone: [
        //   {
        //     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        //     message: "请输入正确的手机号码",
        //     trigger: "blur"
        //   }
        // ]
      },

      base_url: process.env.VUE_APP_BASE_API,
      activeRows: [], // 转换为列表的数据
      newIndex: 0, // 新增值
      oldIndex: 0, // 旧值
      loading_options: false, // 加载状态
      project_list: [], // 项目列表
      img_ground_flage: false, // 图片全屏弹框
      showPreview: false, // 鼠标移入预览图片
    };
  },
  created() {
    // this.getList();
  },
  mounted() {
    this.rowDrop();
  },
  methods: {
    // 远程搜索方法
    querySearchAsync(queryString, cb) {
      let ancestors = ''
      // 判断是组件还是工序
      if (this.titleJson.name == '组件名称') {
        ancestors = `0,100,___,___`
      } else if (this.titleJson.name == '工序名称') {
        ancestors = `0,100,___,___,___`
      }

      selectDateNo({ ancestors, name: queryString }).then(response => {
        cb(response.data)
      })
    },
    // 远程搜索选择的值
    handleSelect(item) {
      // 更新选择的值
      this.form.leader = item.leader
      this.form.phone = item.phone
      this.form.status = item.status
      this.form.email = item.email
      this.form.tableData = item.tableData ? JSON.parse(item.tableData) : []
    },
    // 图片编辑弹框
    click_img_ground() {
      this.img_ground_flage = true
    },
    // 编辑图片确认人按钮
    img_ground_flage_btn() {
      // 调用子组件的方法
      let flag = this.$refs.img_ground.saveCanvas();
      if (flag) {
        // 保存图片编辑格式
        this.form.leader = flag;
        // 保存图片为base64格式
        this.form.phone = this.$refs.img_ground.saveAsImage();
        this.img_ground_flage = false
      }
    },
    // 添加新行
    addRow() {
      let id = this.form.tableData.length + 1;
      this.form.tableData.push({ id, name: '', age: '', address: '' });
    },
    // 删除指定行
    deleteRow(index) {
      this.form.tableData.splice(index, 1);
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then(response => {
        const depts = this.handleTree(response.data, "deptId");
        this.deptList = depts;
        this.loading = false;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 获取选择的层级
    getTreeNodeLevel(treeData, targetKey, level = 0) {
      for (let i = 0; i < treeData.length; i++) {
        const node = treeData[i];
        if (node.deptId === targetKey) {
          return level;
        }
        if (node.children) {
          const childLevel = this.getTreeNodeLevel(node.children, targetKey, level + 1);
          if (childLevel !== undefined) {
            return childLevel;
          }
        }
      }
    },
    // 将树数据转化为平铺数据
    treeToTile(treeData, childKey = 'children') {
      const arr = []
      const expanded = data => {
        if (data && data.length > 0) {
          data.filter(d => d).forEach(e => {
            arr.push(e)
            expanded(e[childKey] || [])
          })
        }
      }
      expanded(treeData)
      return arr
    },
    rowDrop() {
      const tbody = this.$refs.table1.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      Sortable.create(tbody, {
        animation: 300,
        //选择的时候记住拖拽节点的索引
        onChoose: ({ oldIndex }) => {
          this.oldIndex = oldIndex
        },
        onMove: (customEvent, dragEvent) => {
          //移动到新节点会有新节点的索引，和拖拽节点的父id进行
          //比较，如果不一致，不让拖拽，返回false

          this.activeRows = this.treeToTile(this.deptList) // 把树形的结构转为列表再进行拖拽
          this.newIndex = customEvent.related.rowIndex
          const newData = this.activeRows.at(this.newIndex)
          const delData = this.activeRows.at(this.oldIndex)
          if (newData.ancestors != delData.ancestors) {
            return false
          }
        },
        onEnd: ({ newIndex, oldIndex }) => {
          this.oldIndex = oldIndex
          //oldIndex为拖动一行原来的位置，newIndex为拖动后新的位置
          if (oldIndex !== newIndex) { // 根据自己项目需求增添条件限制
            const oldRow = this.activeRows[oldIndex] // 移动的那个元素
            const newRow = this.activeRows[newIndex] // 新的元素
            // 请求接口排序，根据后端要求填写参数
            // 替换位置,orderNum排序,请求接口排序
            // 生成请求参数
            const params = {
              oldDeptId: oldRow.deptId,
              oldOrderNum: newRow.orderNum,
              newDeptId: newRow.deptId,
              newOrderNum: oldRow.orderNum
            }
            //请求接口
            updateDeptOrder(params).then(res => {
              if (res.code === 200) {
                this.$message.success('排序成功')
                this.deptList = []
                this.getList()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        deptNum: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0",
        tableData: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.deptId;
      }
      this.open = true;
      this.title = "添加部门";
      listDeptExcludeChild(row.deptId).then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
        this.setTitle()
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDept(row.deptId).then(response => {
        this.form = response.data;
        // 把字符串转成tableData格式 并且判断是否存在
        this.form.tableData = this.form.tableData ? JSON.parse(this.form.tableData) : []
        this.open = true;
      });
      this.title = "修改部门";
      listDeptExcludeChild(row.deptId).then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
        this.setTitle()
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      // 单独判断项目编号有没有填写
      if (!this.form.deptNum && this.form.parentId == 100) {
        this.$modal.msgError("请填写项目编号");
        return
      }
      // 判断是添加还是修改
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 把tableData转成字符串格式存储 并且判断是否填写
          let tableData = this.form.tableData.length > 0 ? JSON.stringify(this.form.tableData) : undefined
          if (this.form.deptId != undefined) {
            updateDept({ ...this.form, tableData: tableData }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDept({ ...this.form, tableData: tableData }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项？').then(function () {
        return delDept(row.deptId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 修改标题名字和项目名称
    setTitle() {
      let level = this.getTreeNodeLevel(this.deptOptions, this.form.parentId);
      let falg = this.title == '添加部门';
      if (level == 0 && this.title == `${falg ? '添加' : '修改'}部门`) {
        this.titleJson.title = `${falg ? '添加' : '修改'}项目`;
        this.titleJson.name = "项目名称";
      } else if (level == 1 && this.title == `${falg ? '添加' : '修改'}部门`) {
        this.titleJson.title = `${falg ? '添加' : '修改'}设备`;
        this.titleJson.name = "设备名称";
      } else if (level == 2 && this.title == `${falg ? '添加' : '修改'}部门`) {
        this.titleJson.title = `${falg ? '添加' : '修改'}组件`;
        this.titleJson.name = "组件名称";
      } else if (level == 3 && this.title == `${falg ? '添加' : '修改'}部门`) {
        this.titleJson.title = `${falg ? '添加' : '修改'}工序`;
        this.titleJson.name = "工序名称";
      }
    },
    //图片上传成功
    handleImgUplaoded(imgUrl) {
      console.log(imgUrl);
      this.form.email = imgUrl;
    },
    //图片移除
    handleImgRemoved(imgUrl) {
      console.log(imgUrl);
      this.form.email = null;
    },
    changeFun() {
      this.apiFun(this.queryParams.deptName, 1)
      // 调用接口
      this.handleQuery()
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading_options = true;
        this.apiFun(query);
      }
    },
    apiFun(name, type) {
      listDeptPost({ deptName: name }).then(res => {
        this.loading_options = false;
        const resData = res;
        let device_list = []
        if (resData.data.length == 0) {
          this.project_list = []
          device_list = []
          return
        }
        // 拼接项目数据
        this.project_list = resData.data.map(item => {
          return { value: item.deptId, label: item.deptName + '--' + item.deptNum };
        });
        // 拼接设备数据
        device_list = resData.child.map(item => {
          return { value: item.dept_id, label: item.dept_name };
        })
        if (type == 1) {
          this.$notify({
            title: '获取设备成功',
            message: '当前设备数量为 ' + device_list.length,
            type: 'success'
          });
        }
      })
    },
  },
  // 监听树表格展开变化
  watch: {
    "form.parentId": function (val, oldVal) {
      this.setTitle()
    }
  }
};
</script>

<style lang="scss" scoped>
.scroll-container {
  position: relative;
  display: inline-block;
  width: 100%;
  overflow: hidden;
  height: 52px;
}

.scroll-input {
  position: absolute;
  z-index: 2;
}

.scroll-text {
  position: absolute;
  white-space: nowrap;
  animation: scroll-text 5s linear infinite;
  z-index: 1;
  color: rgba(0, 0, 0, 0.5);
  /* 淡化颜色以区分 */
  pointer-events: none;
  /* 避免遮挡输入 */
  top: 35px;
}

@keyframes scroll-text {
  from {
    transform: translateX(100%);
  }

  to {
    transform: translateX(-100%);
  }
}

.img_box {
  // background: red;
  width: 100%;
  height: 80vh;
}
</style>